<?php

/**
 *   OPENSHOP 颜色属性相关设置
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: color.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require_once(dirname(__FILE__).'/includes/init.php');
$exc = new exchange($os->table('color'),$db,'color_id','color_name');
	
/* act操作项的初始化 */
if (empty($_REQUEST['act'])){
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}

if($_REQUEST['act']=='list')
{	
	//检查权限
	admin_priv();
	
	$smarty->assign('ur_here',      '商品颜色');   
	$smarty->assign('action_link',  array('href' => 'color.php?act=add', 'text' => '添加颜色'));
	$color_list = get_colorlist();
	$smarty->assign('color_list',   $color_list['color']);
    $smarty->assign('filter',       $color_list['filter']);
    $smarty->assign('record_count', $color_list['record_count']);
    $smarty->assign('page_count',   $color_list['page_count']);		

	$smarty->assign('full_page',    1);
	
    assign_query_info();    
	$smarty->display('color_list.tpl');	
}
elseif($_REQUEST['act']=='add')
{
	/* 权限检查 */
    admin_priv('add_color');
    
    $smarty->assign('ur_here',      '添加颜色');   
	$smarty->assign('action_link',  array('href' => 'color.php?act=list', 'text' => '颜色管理'));
	$smarty->assign('form_act',     'insert');
	
	assign_query_info();	
	$smarty->display('color_info.tpl');	
}
elseif($_REQUEST['act']=='insert')
{
	/* 权限检查 */
    admin_priv('add_color');	
    
    /*检查颜色名是否相同*/
    $is_only = $exc->is_only('color_name', $_POST['color_name']);
    if (!$is_only)
    {
        sys_msg(sprintf("颜色名称 %s 已经存在！", stripslashes($_POST['color_name'])), 1);
    }
    
    /*检查代码是否相同*/
    $is_only = $exc->is_only('color_code', $_POST['color_code']);
    if (!$is_only)
    {
        sys_msg(sprintf("颜色代码 %s 已经存在！", stripslashes($_POST['color_code'])), 1);
    }

    $imgfile_name = '';    
    if($filesync->sync_type=='ftp'){
    	$filesync->connect();
    	$filesync->setting('color', 'data/color_img', FALSE);
	    $affix_data = $filesync->put_up($_FILES['img_file']);
	    if ($affix_data !== false)
	    {
	        $imgfile_name = $affix_data['virtual_path'];
	    }
	    $filesync->quit();
    }else{
    	$imgfile_name = $filesync->upload_image($_FILES['img_file'],'color_img');
    }
       
    /*插入数据*/
    $sql = "INSERT INTO ".$os->table('color')." (color_code,color_name,color_note,img_id) VALUES ('$_POST[color_code]', '$_POST[color_name]', '$_POST[color_note]','$_POST[img_id]')";
    $db->query($sql);

    admin_log($_POST['color_name'],'add','color');  
    
    /* 清除缓存 */
    clear_cache_files();      
    /*添加链接*/
    $link[0]['text'] = '继续添加颜色';
    $link[0]['href'] = 'color.php?act=add';

    $link[1]['text'] = '返回颜色列表';
    $link[1]['href'] = 'color.php?act=list';

    sys_msg('新颜色添加成功！', 0, $link);
    
}elseif($_REQUEST['act']=='drop_color_img'){
    /* 权限判断 */
    //admin_priv('drop_color_lib');
    
//    $color_id = intval($_GET['color_id']);
//    
//    $sql = "SELECT color_id,img_file FROM " .$os->table('color'). " WHERE color_id = '$color_id'";
//    $color_row = $db->getRow($sql);
//
//    if ($color_row['color_id']>0){
//        if($filesync->sync_type=='ftp'){
//		    $filesync->connect();
//		    @$filesync->drop($color_id, 'color');
//		    $filesync->quit();		    		
//    	}else{
// 		    if (!empty($color_row['img_file'])){
//		        @unlink(SOURCE_PATH .$color_row['img_file']);
//		    }	    		
//    	}
//    		    
//        $sql = "UPDATE " .$os->table('color'). " SET img_file = '' WHERE color_id = '$color_id'";
//        $db->query($sql);
//    }
//    $link= array(array('text' => '重新编辑该颜色', 'href' => 'color.php?act=edit&color_id=' . $color_id), array('text' => '返回列表页面', 'href' => 'color.php?act=list'));
//    sys_msg('删除颜色图标成功', 0, $link);
}elseif($_REQUEST['act']=='edit'){

    /* 权限判断 */
    admin_priv('edit_color');
    
    $sql = "SELECT c.color_id, c.color_code, c.color_name, c.color_note, cl.* FROM " . $os->table('color') . 
           " c LEFT JOIN ". $GLOBALS['os']->table('color_lib') ." cl ON c.img_id=cl.img_id ".
           " WHERE c.color_id=" . intval($_GET['color_id']);
    $color = $db->GetRow($sql);
	$img_item = '';
	if($color['img_id']>0 && !empty($color['img_file'])){
	 	$img_item = '<a href="'.$_CFG['pre_fetch_img'].$color['img_file'].'?16,16" target="_brank">
	                 	<img src="'.$_CFG['pre_fetch_img'].$color['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$color['img_name'].'"/>
	                 </a>';  
	}	    	
    $color['img_item']  = 	$img_item;
    $smarty->assign('ur_here',     '编辑颜色记录');
    $smarty->assign('action_link', array('text' => '颜色管理', 'href' => 'color.php?act=list&' . list_link_postfix()));
    $smarty->assign('color',       $color);
    $smarty->assign('form_act',    'updata');

    assign_query_info();	
	$smarty->display('color_info.tpl');	
}
elseif($_REQUEST['act']=='updata')
{
	/* 权限判断 */
	admin_priv('edit_color');

    if ($_POST['color_name'] != $_POST['old_color_name'])
    {
        /*检查颜色名是否相同*/
        $is_only = $exc->is_only('color_name', $_POST['color_name'], $_POST['color_id']);

        if (!$is_only)
        {
            sys_msg(sprintf("颜色名称 %s 已经存在！", stripslashes($_POST['color_name'])), 1);
        }
    }
    if ($_POST['color_code'] != $_POST['old_color_code'])
    {
        /*检查颜色代码是否相同*/
        $is_only = $exc->is_only('color_code', $_POST['color_code'], $_POST['color_id']);

        if (!$is_only)
        {
            sys_msg(sprintf("颜色代码 %s 已经存在！", stripslashes($_POST['color_code'])), 1);
        }
    } 

//    $imgfile_name = '';
//    if($filesync->sync_type=='ftp'){
//    	$filesync->connect();
//    	$filesync->setting('color', 'data/color_img', FALSE);
//    	$filesync->set_updata(TRUE, $_POST['color_id'], 'color');
//	    $affix_data = $filesync->put_up($_FILES['img_file']);
//	    if ($affix_data !== false)
//	    {
//	        $imgfile_name = $affix_data['virtual_path'];
//	    }
//	    $filesync->quit();
//    }else{
//    	$imgfile_name = $filesync->upload_image($_FILES['img_file'],'color_img');
//    }
    
	$param = "img_id='$_POST[img_id]',color_code = '$_POST[color_code]',  color_name='$_POST[color_name]', color_note='$_POST[color_note]' ";	    
    if ($exc->edit($param,  $_POST['color_id']))
    {
        /* 清除缓存 */
        clear_cache_files();

        admin_log($_POST['color_name'], 'edit', 'color');

        $link[0]['text'] = "返回颜色列表";
        $link[0]['href'] = 'color.php?act=list';
        $note = vsprintf("颜色 %s 修改成功！", $_POST['color_name']);
        sys_msg($note, 0, $link);
    }
    else
    {
        die($db->error());
    }
}elseif ($_REQUEST['act'] == 'remove'){
	/* 权限判断 */
    check_authz_json('drop_color');
    
    $color_id = intval($_GET['id']);
 
    $color_name = $db->getOne('SELECT color_name FROM ' .$os->table('color'). " WHERE color_id='$color_id'");
    
    $cat_rel_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('category_color'). " WHERE color_id='$color_id'");
    
    $goods_rel_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('goods_color'). " WHERE color_id='$color_id'");

    $sql = "SELECT img_file FROM " .$os->table('color'). " WHERE color_id = '$color_id'";
    $color_row = $db->getRow($sql);    
     
    if($color_row['img_file'] != ''){    
    
    	if($cat_rel_count==0 && $goods_rel_count==0){

//    		if($filesync->sync_type=='ftp'){
//    			$filesync->connect();
//    			@$filesync->drop($color_id, 'color');
//    			$filesync->quit();
//    		}else{
//    			if (!empty($color_row['img_file'])){
//    				@unlink(SOURCE_PATH . $color_row['img_file']);
//    			}
//    		}

    		/* 删除该颜色 */
    		if($exc->drop($color_id)){
    			admin_log($color_name, 'remove', 'color');
    		}

    	}else{
    		make_json_error('"'.$color_name .'" 该颜色与商品、分类还有关联,您不能删除!');
    	}
    }
    
    $url = 'color.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
    os_header("Location: $url\n");
    exit;
}elseif ($_REQUEST['act'] == 'query'){
    $color_list = get_colorlist();

    $smarty->assign('color_list',   $color_list['color']);
    $smarty->assign('filter',       $color_list['filter']);
    $smarty->assign('record_count', $color_list['record_count']);
    $smarty->assign('page_count',   $color_list['page_count']);

    make_json_result($smarty->fetch('color_list.tpl'), '',
        array('filter' => $color_list['filter'], 'page_count' => $color_list['page_count']));
}elseif($_REQUEST['act']=='relevancy'){
	/* 权限检查 */
    admin_priv('relevancy_cate_color');	
    
    $smarty->assign('ur_here',      '关联设置'); 
	$smarty->assign('action_link',  array('href' => 'color.php?act=list', 'text' => '颜色管理'));
	$color_id = $db->getOne("SELECT color_id FROM ".$os->table('color')." WHERE color_id=".intval($_GET['color_id']));
	$smarty->assign('cat_color_list',get_cat_color_list(intval($_GET['color_id'])));
	$smarty->assign('color_id',$color_id);
	
	assign_query_info();
	$smarty->display('color_relevancy.tpl');	
}
/*------------------------------------------------------ */
//-- 搜索色卡
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_color_lib_list'){	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;
    $filter = $json->decode($_GET['JSON']);

    $where = " WHERE 1 ";
  	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ? " AND (img_name LIKE '%" . mysql_like_quote($filter->keyword)."%') OR (img_code LIKE '%" . mysql_like_quote($filter->keyword) . "%')" : '';
    $sql = 'SELECT * FROM ' . $os->table('color_lib') . $where . ' ORDER BY img_id DESC LIMIT 50';
    $res = $db->query($sql);
    $opt = array();
    while ($row = $db->fetchRow($res)){
    	$img_item = '';
    	if(!empty($row['img_file']))
        	$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$row['img_name'].'"/>';
        $opt[]  = array('value' => $row['img_id'], 'text' => $row['img_name'], 'code'=>$row['img_code'], 'img_item'=>$img_item);
    }
    
    make_json_result($opt);
    
}elseif($_REQUEST['act'] == 'set_default_colorlib'){	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;
    $filter = $json->decode($_GET['JSON']);
    
    $sql = "SELECT * FROM " . $os->table('color_lib') . " WHERE img_id='$filter->img_id' LIMIT 1";
    $row = $db->getRow($sql);
 	$img_item = '';
	if(!empty($row['img_file']))
    	$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$row['img_name'].'"/>';   
    	
    $opt = array('value' => $row['img_id'], 'text' => $row['img_name'], 'code'=>$row['img_code'], 'img_item'=>$img_item);
    
    make_json_result($opt);	
    
}elseif($_REQUEST['act']=='search_cat'){
    /* 检查权限 */
    check_authz_json('relevancy_cate_color');

    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json   = new JSON;
    $filter = $json->decode($_GET['JSON']);
    $filter->keyword = json_str_iconv($filter->keyword);	
    $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $os->table('category') .
        " WHERE cat_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
    $arr = $db->getAll($sql);
    if (empty($arr)){
        $arr = array(0 => array(
            'id'   => 0,
            'name' => '没有找到相应记录，请重新搜索'
        ));
    }

    make_json_result($arr);	
    
}elseif ($_REQUEST['act']=='add_cat_color'){
	
	check_authz_json('relevancy_cate_color');
	
    include_once(ROOT_PATH . 'includes/cls_json.php');    
    $json = new JSON;

    $cat_ids   = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $color_id   = $arguments[0];
    $color_name = $db->getOne("SELECT color_name FROM " . $os->table('color') . " WHERE color_id='$color_id'");
    foreach ($cat_ids as $val){
	    $sql = "INSERT INTO " . $os->table('category_color') . " VALUES(null,'$val','$color_id','$color_name')";
	    $db->query($sql);
    }

    $arr = get_cat_color_list($color_id);
    $opt = array();
    
    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['cat_id'],
                        'text'      => $val['cat_name'],
                        'data'      => '');
    }
    
    clear_cache_files();
    
    make_json_result($opt);
    
}elseif($_REQUEST['act']=='drop_cat_color'){
	
	check_authz_json('relevancy_cate_color');
	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $cat_ids   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $color_id   = $arguments[0];
    $sql = "DELETE FROM " .$os->table('category_color') . " WHERE color_id='$color_id' AND " . db_create_in($cat_ids, "cat_id");
    $db->query($sql);

    $arr = get_cat_color_list($color_id);
    $opt = array();
    
    foreach ($arr AS $val){
        $opt[] = array('value'      => $val['cat_id'],
                        'text'      => $val['cat_name'],
                        'data'      => '');
    }
    
    clear_cache_files();
    make_json_result($opt);	
}

function get_colorlist(){
	global $_CFG;
    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array();

        $filter['keyword']  = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);

        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }        
        
        if ($filter['keyword'])
        {
			$where .= " AND (c.color_code LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR c.color_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }     
                
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('color').' c where 1 '.$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 查询记录 */
		$sql = "SELECT c.color_id,c.color_code,c.color_name,c.color_note,cl.img_file FROM ". $GLOBALS['os']->table('color')." c LEFT JOIN ". 
		        $GLOBALS['os']->table('color_lib')." cl ON c.img_id=cl.img_id where 1 ".$where." ORDER BY c.color_id DESC";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);
    
    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $img_item = '<a href="'.$_CFG['pre_fetch_img'].$rows['img_file'].'?16,16" target="_brank">
                     <img src="'.$_CFG['pre_fetch_img'].$rows['img_file'].'?16,16" width="16" height="16" border="0" 	alt="'.$rows['img_name'].'"/>
                     </a>';
       
        $rows['img_item'] = $img_item;

        $arr[] = $rows;
    }	
    return array('color' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

function get_cat_color_list($color_id=0){
	static $rows = NULL;
	
	$sql = "SELECT c.cat_name,c.cat_id FROM ".$GLOBALS['os']->table('category_color').
	       " c_c LEFT JOIN ".$GLOBALS['os']->table('category')." c ON c_c.cat_id=c.cat_id";
	if($color_id>0){
		$sql .= " WHERE c_c.color_id = '$color_id'";
	}
	$sql .= " ORDER BY c_c.cat_color_id DESC";
	if ($rows === NULL){
		$rows = $GLOBALS['db']->getAll($sql);
	}
	return $rows;		
}
?>